<template>
  <div>
    <!-- 评论列表 -->
    <div class="cmt-list">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
        :immediate-check="false"
      >
        <!-- 评论的 Item 项 -->
        <div
          class="cmt-item"
          v-for="(item, index) in artcommentList"
          :key="index"
        >
          <!-- 头部区域 -->
          <div class="cmt-header">
            <!-- 头部左侧 -->
            <div class="cmt-header-left">
              <img :src="item.aut_photo" alt="" class="avatar" />
              <span class="uname">{{ item.aut_name }}</span>
            </div>
            <!-- 头部右侧 -->
            <div class="cmt-header-right">
              <van-icon
                @click="loveFn(false, item)"
                v-if="item.is_liking"
                name="like"
                size="16"
                color="red"
              />
              <van-icon
                @click="loveFn(true, item)"
                v-else
                name="like-o"
                size="16"
                color="gray"
              />
            </div>
          </div>
          <!-- 主体区域 -->
          <div class="cmt-body">
            {{ item.content }}
          </div>
          <!-- 尾部区域 -->
          <div class="cmt-footer">{{ item.pubdate }}</div>
        </div>
      </van-list>
    </div>
    <!-- 评论组件 -->
    <!-- 底部添加评论区域 - 1 -->
    <div class="add-cmt-box van-hairline--top" v-if="isShowCmtInput === false">
      <van-icon name="arrow-left" size="0.48rem" @click="$router.back()" />
      <div class="ipt-cmt-div" @click="isShowCmtInput = !isShowCmtInput">
        发表评论
      </div>
      <div class="icon-box">
        <van-badge
          :content="totalCount"
          max="99"
          @click.native="scrollToViewFn"
        >
          <van-icon name="comment-o" size="0.53333334rem" />
        </van-badge>
        <van-icon
          name="star"
          size="0.53333334rem"
          v-if="artObj.is_collected"
          @click="toggleColleFn"
        />
        <van-icon
          name="star-o"
          size="0.53333334rem"
          v-else
          @click="toggleColleFn"
        />
        <van-icon name="share-o" size="0.53333334rem" />
      </div>
    </div>

    <!-- 底部添加评论区域 - 2 -->
    <div class="cmt-box van-hairline--top" v-else>
      <textarea
        v-model.trim="cmtStr"
        placeholder="友善评论、理性发言、阳光心灵"
        v-focus
        @keydown.enter="publishcmtFn"
        @blur="isShow"
      ></textarea>
      <van-button
        type="default"
        :disabled="cmtStr.length === 0"
        @click="publishcmtFn"
        >发布</van-button
      >
    </div>
  </div>
</template>

<script>
// 引入评论接口
import {
  getArtCommentAPI,
  dislikecommentAPI,
  likecommentAPI,
  publishcmtAPI
} from '../../api/article'
// 引入时间转换组件
import { timeAgo } from '@/utils/date'
import { Toast } from 'vant'

export default {
  name: 'comment',
  props: {
    artObj: {
      type: Object,
      require: true
    }
  },
  data () {
    return {
      artcommentList: [], // 评论列表
      isShowCmtInput: false, // 评论盒子互斥显示
      totalCount: '', // 评论总数
      cmtStr: '', // 评论内容
      loading: false, // 上拉继续加载
      finished: false // 终止下拉
    }
  },
  created () {
    this.getcommentListFn()
  },

  methods: {
    // 注册事件组件
    timeAgo,
    // 评论是否喜欢
    async loveFn (boolean, item) {
      try {
        // 修改后台数据
        boolean
          ? await likecommentAPI({ cmtId: item.com_id })
          : await dislikecommentAPI({ cmtId: item.com_id })
        Toast.success(!boolean ? '取消点赞成功!' : '点赞成功!')
        // 修改vue本地数据
        item.is_liking = boolean
      } catch (err) {
        Toast.fail(!boolean ? '取消点赞失败!' : '点赞失败!')
      }
    },
    // 点击按钮滚动到评论区
    scrollToViewFn () {
      document.getElementById('like-box').scrollIntoView({
        behavior: 'smooth'
      })
    },
    // 发布评论方法
    async publishcmtFn () {
      try {
        if (!this.cmtStr) return Toast('请输入评论内容!')
        // 把评论的内容添加到commentlist数组中,并同步到后台
        const res = await publishcmtAPI({
          artId: this.artObj.art_id,
          data: this.cmtStr
        })
        console.log(res)
        // 发送的数据获取对象再添加到数组中
        const { new_obj: newobj } = res.data

        newobj.pubdate = this.timeAgo(newobj.pubdate)

        this.artcommentList.unshift(newobj)
        this.cmtStr = ''
        Toast.success('发布成功!')
        this.isShow()
        this.getcommentListFn()
      } catch (err) {
        Toast.fail('发布失败!')
      }
    },
    // 失去焦点显示隐藏盒子
    isShow () {
      setImmediate(() => {
        this.isShowCmtInput = false
      })
    },
    // 公共方法获取评论数据
    async getcommentListFn () {
      try {
        const res = await getArtCommentAPI({
          artId: this.artObj.art_id,
          offset: this.offset
        })

        // 时间转换
        res.data.results.forEach((obj) => {
          obj.pubdate = this.timeAgo(obj.pubdate)
        })

        // 获取的评论数据赋值给本地的数组
        this.artcommentList = [...this.artcommentList, ...res.data.results]
        const { total_count: sum, last_id: lastId } = res.data
        // 获取最后一次的last_id值,下次请求需要携带
        this.offset = lastId
        // 评论的总条数
        this.totalCount = sum || ''
        // 每次执行继续加载数据
        this.loading = false
        // 数据不够将不再加载数据
        if (res.data.results.length < 10 || res.last_id === null) {
          this.finished = true
        }
      } catch (err) {
        throw new Error(err)
      }
    },
    // 上拉触发的事件
    onLoad () {
      this.getcommentListFn()
    },
    // 点击是否收藏
    toggleColleFn () {
      try {
        Toast.success(
          !this.artObj.is_collected ? '收藏成功!' : '取消收藏成功!'
        )
        this.artObj.is_collected = !this.artObj.is_collected
      } catch (err) {
        Toast.fail(!this.artObj.is_collected ? '收藏失败!' : '取消收藏失败!')
      } finally {
      }
    }
  }

}
</script>

<style scoped lang="less">
.cmt-list {
  padding: 10px;
  margin-bottom: 26px;
  .cmt-item {
    padding: 15px 0;
    + .cmt-item {
      border-top: 1px solid #f1f1f1;
    }
    .cmt-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .cmt-header-left {
        display: flex;
        align-items: center;
        .avatar {
          width: 40px;
          height: 40px;
          background-color: #f8f8f8;
          border-radius: 50%;
          margin-right: 15px;
        }
        .uname {
          font-size: 12px;
        }
      }
    }
    .cmt-body {
      font-size: 14px;
      line-height: 28px;
      text-indent: 2em;
      margin-top: 6px;
      word-break: break-all;
    }
    .cmt-footer {
      font-size: 12px;
      color: gray;
      margin-top: 10px;
    }
  }
}
/*美化 - 文章详情 - 底部的评论页面 */
// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    margin-left: 10px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}
</style>
